package peter.hello;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/greeting")
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value = "name", required = false, defaultValue = "World") String name,
                    Model model) {
        model.addAttribute("name", name);
        System.out.println(">>>>> greeting");
        return "greeting1";
    }

    @RequestMapping(value = "/showCookies", produces = "text/plan;charset=UTF-8")
    public void showCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();// 这样便可以获取一个cookie数组
        String str = "";

        if(null == cookies) {
            str = ">>> 没有数据";
            System.out.println(str);
        }
        else {
            for(Cookie cookie : cookies) {
                System.out.println(">>> name:" + cookie.getName() + ",value:" + cookie.getValue());
                str += ">>> name:" + cookie.getName() + ",value:" + cookie.getValue() + "<br/>";
            }
        }

        response.getWriter().write(str);
    }

    @RequestMapping(value = "/setCookies", produces = "text/plan;charset=UTF-8")
    public void setCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();// 这样便可以获取一个cookie数组
        String str = "";

        if(null == cookies) {
            str = ">>> 没有数据";
            System.out.println(str);
        }
        else {
            for(Cookie cookie : cookies) {
                System.out.println(">>> name:" + cookie.getName() + ",value:" + cookie.getValue());
                str += ">>> name:" + cookie.getName() + ",value:" + cookie.getValue() + "<br/>";
            }
        }

        response.addCookie(new Cookie("key", "name"));
        response.getWriter().write(str);
    }
}
